package com.qidian.mes.qc.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.pojo.QcDefect;
import com.qidian.mes.qc.mapper.DefectMapper;
import com.qidian.mes.qc.service.DefectService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @Author 朱静炜
 * @Company 起点编程
 * @Time 2023/10/25 18:14
 * @Description
 */
@Service
public class DefectServiceImpl implements DefectService {
    @Autowired
    private DefectMapper defectMapper;

    @Override
    public MESResult delete(Long defectId) {
        QcDefect qcDefect = defectMapper.getById(defectId);
        if (qcDefect == null)
            return MESResult.fail("对象不存在");
        return MESResult.ok(defectMapper.deleteByDefectId(defectId));
    }

    @Override
    public MESResult getById(Long defectId) {
        return MESResult.ok(defectMapper.getById(defectId));
    }

    @Override
    public MESResult update(QcDefect qcDefect) {
        return MESResult.updateIsOk(defectMapper.update(qcDefect));
    }

    @Override
    public MESResult save(QcDefect qcDefect) {
        Random random = new Random();
        if (qcDefect.getDefectName() != null || qcDefect.getIndexType() != null || qcDefect.getDefectLevel() != null){
            qcDefect.setDefectCode(Integer.toString(random.hashCode()));//随机生产Hash值作为缺陷编号
            return MESResult.ok(defectMapper.save(qcDefect));
        }
        return MESResult.empty("数据为空");
    }

    @Override
    public MESResult list(QcDefect qcDefect, int page, int limit) {
        PageHelper.startPage(page,limit);
        List<QcDefect> list = defectMapper.list(qcDefect);
        // 组织一个分页对象。（页码，每页大小，最大页码，数据，总条数）
        PageInfo<QcDefect> pageInfo = new PageInfo<>(list);
        return MESResult.ok(pageInfo);
    }
}
